/*
 *	stringext.c
 *	© 2009 Tom Booth
 *
 *	A set of useful functions for working with strings
 *
 */

#include <stdlib.h>
#include <string.h>

#include "stringext.h"

int string_extract(char **in, char **out, int start, int length) {
	int in_len, overhang, i;
	
	// extract the string to spit out
	// allocate enough space for string and null terminator
	*out = malloc(sizeof(char) * (length+1));
	
	// copy the string and append a null at the end
	strncpy(*out, *in+(start*sizeof(char)), length);
	(*out)[length] = '\0';
	
	// rejig the characters in the string in
	in_len = strlen(*in);
	
	if (in_len <= (start+length)) {
		// if theres nothing beyond extracted string just chop it off
		overhang=0;
	}
	else {
		// move characters down over extracted string
		overhang = in_len - (start+length);
		for (i=0; i<overhang; i++) {
			(*in)[start+i] = (*in)[start+length+i];
		}
	}
	
	*in = realloc(*in, sizeof(char) * (start+overhang+1));
	
	(*in)[start+overhang] = '\0';
	
	return 0;
}







